import functools
import logging
import os

from google.appengine.api import memcache


DEBUG = os.environ['SERVER_SOFTWARE'].startswith('Development')
CACHE_LEN = 60 * 60 if not DEBUG else 1


def memcache_get(fxn):
    """Decorator to try to get the information from memcache before doing the
    actual GET request."""
    @functools.wraps(fxn)
    def get(self, *args, **kwargs):
        assert not self.request.query_string
        key = self.request.path
        cached = memcache.get(key)
        if cached is not None:
            self.response.out.write(cached)
        else:
            fxn(self, *args, **kwargs)
            memcache.add(key, self.response.body, CACHE_LEN)

    return get


def cache_control(fxn):
    """Decorator to use the HTTP Cache-Control header."""
    @functools.wraps(fxn)
    def get(self, *args, **kwargs):
        self.response.headers.add_header('Cache-Control',
                                         'max-age=%s' % CACHE_LEN)
        fxn(self, *args, **kwargs)
    return get

